<?php

namespace Beerus\Modules\DesignerOrder\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Biz\pockets\excel\DownExcel;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerOfflinePay;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerOrder;
use Doraemon\model\DesignerOrderRefund;
use Doraemon\model\DesignerPackage;
use Doraemon\model\DesignerPayService;
use Doraemon\model\Member;
use Doraemon\service\Designer\AuthService;
use Doraemon\service\Designer\DesignerDingTalkAlert;
use Doraemon\service\Designer\DesignerEquityService;
use Doraemon\service\Designer\DesignerService;
use Doraemon\service\Designer\OrderRefund;
use Doraemon\service\Designer\OrderSN;
use Doraemon\service\DingTalkAlert;
use Doraemon\service\WechatAlert;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\model\AdmSaleBind\AdmSaleBind;

class DesignerOrderController extends Controller
{
	const PAGE_SIZE = 20;

	// 订单状态
	const ORDER_STATUS = [
		1 => '创建订单',
		2 => '完成订单',
		3 => '取消订单',
	];

	// 支付方式
	const PAY_PLATFORM = [
		1 => '支付宝',
		2 => '微信',
		3 => '银行转账',
	];

	// 支付状态
	const PAY_STATUS = [
		1 => '未支付',
		2 => '已支付',
		3 => '支付失败',
	];

	// 结算状态
	const SETTLE_STATUS = [
		1 => '未结算',
		2 => '已结算',
	];

	// 退款状态
	const HAVE_NOT_REFUND = 1;
	const APPLY_REFUND = 2;
	const PASS_REFUND = 3;
	const HAD_REFUND = 4;

	const REFUND_STATUS = [
		self::HAVE_NOT_REFUND => '未退款',
		self::APPLY_REFUND => '申请退款',
		self::PASS_REFUND => '审核通过',
		self::HAD_REFUND => '已退款',
	];

	const STATUS = [
		0 => '已删除',
		1 => '正常'
	];

	const UNLIMITED_LIST = [
        'renyuanxia',
        'xingzhiqian',
    ];

	public function __construct()
	{
		parent::__construct();
		Admin::script('$(".pjax-container").attr("id","pjax-container");');
	}

	public function index(Request $request, Content $content, $tab_id = 1)
	{
		$params = $request->all();

		$tab = new Tab();
		$tab->addLink('付费订单列表', '/admin/DesignerOrder/orders/1', $tab_id == 1);
		$tab->addLink('线下付款订单', '/admin/DesignerOrder/orders/2', $tab_id == 2);
		$tab->addLink('退款订单列表', '/admin/DesignerOrder/orders/3', $tab_id == 3);

        if ($tab_id == 1) {
            $row = $this->listAllOrder($request, $params);
        } elseif ($tab_id == 2) {
            $row = $this->listOfflineOrder($request, $params);
        } elseif ($tab_id == 3) {
            $row = $this->listRefundOrder($request, $params);
        }

		return $content
			->header('付费订单管理')
			->breadcrumb(
				['text' => '付费订单列表', 'url' => '/admin/DesignerOrder/orders/'. $tab_id]
			)
			->body($tab)
			->row($row);
	}

	public function listOfflineOrder($request, $params)
	{
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = $this->condition($params);

		$total = DesignerOfflinePay::count($condition);

		$lists = [];
		if (!empty($total)) {
			$condition['ORDER'] = ['id' => 'DESC'];
			$condition['LIMIT'] = [
				($page - 1) * $page_size,
				$page_size
			];

			$lists = DesignerOfflinePay::select('*', $condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);
			$packages = DesignerPackage::select('*', []);
			$map_package = array_column($packages, 'package_name', 'id');

			foreach ($lists as &$item) {
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$item['package_name'] = empty($map_package[$item['package_id']]) ? '-' : $map_package[$item['package_id']];
				$item['status'] = self::STATUS[$item['status']];
			}
			unset($item);
		}

		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => self::PAGE_SIZE
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->disableCreateButton();

				// 添加录入线下付款按钮
				$grid->tools(function (Grid\Tools $tool) use ($grid) {
					$url = url('admin/DesignerOrder/orders/2/create');
					$button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">录入线下付款订单</span></a>
                    </div>';
					$tool->append($button);
				});

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('uid', '用户UID')->placeholder('请输入uid');
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
					});

					$filter->expand();
				});

				$grid->column('uid', '用户UID')->copyable();
				$grid->column('nick', '昵称')->copyable();
				$grid->column('package_name', '套餐名称');
				$grid->column('amount', '实付价格');
				$grid->column('add_time', '录入时间')->display(function () {
					if (empty($this->add_time)) {
						return '-';
					} else {
						return date('Y-m-d H:i:s', $this->add_time);
					}
				});
				$grid->column('pay_proof', '汇款凭证截图')->display(function () {
					if (!empty($this->pay_proof)) {
						$pay_proof = self::getPicUrl($this->pay_proof);
						$img = "<a href='{$pay_proof}' target='_blank'><img style='box-shadow: 0 0 10px 0 rgba(0, 0, 0, .2)' width='100' height='100' src='{$pay_proof}'></a>";
						return implode('<br/>', [$img]);
					}
				});
				$grid->column('admin_id', '操作人')->display(function(){
					if(empty($this->admin_id)) {
						return '-';
					}else{
						$admin_name = Admin::user()->find($this->admin_id)->name;
						return empty($admin_name) ? $this->admin_name : $admin_name;
					}
				});
				$grid->column('status', '数据状态');
				$grid->disableActions();
			}
		);

		return $gridList->render();
	}

	public function listAllOrder($request, $params)
	{
		$page_size = $request->input('per_page', self::PAGE_SIZE);
		$page = $request->input('page', 1);

		$condition = $this->condition($params);

		$condition['ORDER'] = ['id' => 'DESC'];
		$condition['LIMIT'] = [
			($page - 1) * $page_size,
			$page_size
		];

		$lists = DesignerOrder::select('*', $condition);

		$total = 0;
		if (!empty($lists)) {
			unset($condition['ORDER']);
			unset($condition['LIMIT']);
			$total = DesignerOrder::count($condition);
			$user_ids = array_column($lists, 'uid');
			$member_info = Member::getUsers($user_ids);

			foreach ($lists as &$item) {
				$item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
				$item['pay_status'] = self::PAY_STATUS[$item['pay_status']];
				$item['refund_status'] = self::REFUND_STATUS[$item['refund_status']];
			}
			unset($item);
		}

		unset($condition['ORDER'], $condition['LIMIT']);
		$search_params = http_build_query($condition);
		$gridModel = new pGridDataModel($lists, $total, [
			'perPage' => $page_size
		]);
		$gridList = Admin::grid(
			$gridModel,
			function (Grid $grid) use ($gridModel, $search_params, $condition) {
				$grid->paginate($gridModel->getPerPage());
				$grid->disableCreateButton();
				$grid->disableExport();
				$grid->disableRowSelector();
				$grid->header(function () use ($condition) {
					$query = DesignerOrder::select('amount', $condition);
					$total_amount = array_sum($query);
					$total_amount = empty($total_amount) ? 0 : preg_replace('/(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))/', ',', $total_amount);
					return '<b style="color: deepskyblue">收款订单数：</b>'. count($query). '<b style="margin-left: 80px; color: deepskyblue">收款总金额：</b>'. $total_amount;
				});

				// 添加导出按钮
				$grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
					$url = url('/admin/DesignerOrder/orders/export?'. $search_params);
					$button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出订单</span></a>
                    </div>';
					$tool->append($button);
				});

				$grid->filter(function (Grid\Filter $filter) {
					$filter->disableIdFilter();
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('uid', '用户UID')->placeholder('请输入uid');
						$filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                        $filter->equal('dsn', '设计师订单号')->placeholder('请输入设计师订单号');
					});
					$filter->column(1 / 4, function ($filter) {
						$filter->equal('pay_status', '支付状态')->select(self::PAY_STATUS);
						$filter->equal('refund_status', '退款状态')->select(self::REFUND_STATUS);
					});
					$filter->column(1 / 3, function ($filter) {
						$filter->equal('pay_platform', '支付方式')->select(self::PAY_PLATFORM);
						$filter->between('pay_time', '支付时间')->date('Y-m-d');
					});

					$filter->expand();
				});

				$grid->column('dsn', '设计师订单号')->copyable();
				$grid->column('uid', '用户UID')->copyable();
				$grid->column('nick', '用户昵称')->copyable();
				$grid->column('package_name', '套餐名称');
				$grid->column('create_time', '下单时间')->display(function () {
					if (empty($this->create_time)) {
						return '-';
					} else {
						return date('Y-m-d H:i:s', $this->create_time);
					}
				});
				$grid->column('order_status', '订单状态')->display(function () {
					return self::ORDER_STATUS[$this->order_status];
				});
				$grid->column('pay_platform', '支付方式')->display(function () {
					return self::PAY_PLATFORM[$this->pay_platform];
				});
				$grid->column('other_sn', '第三方订单号');
				$grid->column('pay_time', '支付时间')->display(function () {
					if (empty($this->pay_time)) {
						return '-';
					} else {
						return date('Y-m-d H:i:s', $this->pay_time);
					}
				});
				$grid->column('pay_status', '支付状态')->display(function ($title, Grid\Column $column) {
					if ($this->pay_status == '已支付') {
						return $column->label('success');
					} else if ($this->pay_status == '未支付') {
						return $column->label('warning');
					} else if ($this->pay_status == '支付失败') {
						return $column->label('danger');
					} else {
						return '';
					}
				})->width(100);
				$grid->column('refund_status', '退款状态')->display(function ($title, Grid\Column $column) {
					if ($this->refund_status == '未退款') {
						return $column->label('success');
					} else if ($this->refund_status == '已退款') {
                        $label = "<sapn class='label label-danger' style='display:inline-block; margin-bottom: 2px;'>已退款</sapn><br/>";
                        $url = url('/admin/DesignerOrder/orders/3?dsn=');
                        $refund_url = '<a style="font-size:12px" href="' . $url . $this->dsn . '" target="_blank">' . '退款详情' . '</a>';
						return $label . $refund_url;
					} else {
						return '';
					}
				});
				$grid->column('amount', '实际支付金额');
				$grid->column('price', '商品当前价格');
				$grid->column('product_price', '商品定价');
				$grid->column('start_time', '服务生效时间');
				$grid->column('end_time', '服务到期时间');
				$grid->column('customer', '新/老用户');
				$grid->actions(function (Grid\Displayers\Actions $actions) {
					$actions->disableDelete();
				});
			}
		);

		return $gridList->render();
	}

    public function listRefundOrder($request, $params)
    {
        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $condition = $this->condition($params);

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = DesignerOrderRefund::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = DesignerOrderRefund::count($condition);


            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
            }
            unset($item);
        }

        unset($condition['ORDER'], $condition['LIMIT']);
        $search_params = http_build_query($condition);
        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params, $condition) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->header(function () use ($condition) {
                    $query = DesignerOrderRefund::select('refund_amount', $condition);
                    $total_amount = array_sum($query);
                    $total_amount = empty($total_amount) ? 0 : preg_replace('/(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))/', ',', $total_amount);
                    return '<b style="color: deepskyblue">退款订单数：</b>'. count($query). '<b style="margin-left: 80px; color: deepskyblue">退款总金额：</b>'. $total_amount;
                });

                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                    $url = url('/admin/DesignerOrder/orders/exportRefund?'. $search_params);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出订单</span></a>
                    </div>';
                    $tool->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 4, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('dsn', '设计师订单号')->placeholder('请输入订单号');
                        $filter->equal('refund_platform', '退款方式')->select(DesignerOrderRefund::PAY_PLATFORM);
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->between('refund_time', '退款时间')->date('Y-m-d');
                    });

                    $filter->expand();
                });

                $grid->column('dsn', '设计师订单号')->display(function () {
                    $url = url('/admin/DesignerOrder/orders/1?dsn=');
                    return '<a href="' . $url . $this->dsn . '" target="_blank">' . $this->dsn . '</a>';
                });
                $grid->column('uid', '用户UID')->copyable();
                $grid->column('nick', '用户昵称')->copyable();
                $grid->column('package_name', '套餐名称');
                $grid->column('refund_amount', '退款金额');
                $grid->column('refund_time', '退款时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->refund_time);
                });
                $grid->column('refund_platform', '退款方式')->display(function () {
                    return DesignerOrderRefund::PAY_PLATFORM[$this->refund_platform];
                });
                $grid->column('platform_sn', '交易单号');
                $grid->column('reason', '退款原因');
                $grid->column('admin_id', '退款操作人')->display(function(){
                    if(empty($this->admin_id)) {
                        return '-';
                    }else{
                        $admin_name = Admin::user()->find($this->admin_id)->name;
                        return empty($admin_name) ? $this->admin_name : $admin_name;
                    }
                });
            }
        );

        return $gridList->render();
    }

	public function edit(Request $request, Content $content, $tab_id = 1, $id = 0)
	{
		$header = '修改订单';
		$tab = new Tab();
		$tab->add('订单详情', self::editAction($id));
		return $content->header($header)
			->breadcrumb([
				'text' => '付费订单列表',
				'url' => route('order.list', ['tab_id' => $tab_id])
			], ['text' => $header])->row($tab);
	}

	public function editAction($id)
	{
        Admin::script(<<<SCRIPT
		$(document).ready(function(){  
            $(':submit').click(function(e){
                e.preventDefault();
                let refundSlt = $('.refund_status').children('option:selected').val();
                
                if (refundSlt == '') {
                    layer.msg('请选择退款状态');
                    return false;
                } else if (refundSlt == 4) {
                    var refund_amount = $('#refund_amount').val();
                    var refund_time = $('#refund_time').val();
                    var platform_sn = $.trim($('#platform_sn').val());
                    var reason = $.trim($('#reason').val());
                    
                    if (refund_amount == '') {
                        layer.msg('请填写退款金额');
                        return false;
                    }
                    
                    if (/^\d{1,9}([\.][0-9]{1,2})?$/.test(refund_amount) == false) {
                        layer.msg('退款金额格式错误，最多9位整数，2位小数');
                        return false;
                    }
                    
                    var pay_amount = $('#amount').val();
                    if (refund_amount * 100 > pay_amount * 100) {
                        layer.msg('退款金额不能大于实际支付金额');
                        return false;
                    }
                    
                    if (refund_time == '') {
                        layer.msg('请填写退款时间');
                        return false;
                    }
                    
                    if (platform_sn == '') {
                        layer.msg('请填写交易单号');
                        return false;
                    }
                    
                    if (reason == '') {
                        layer.msg('请填写退款原因');
                        return false;
                    }
                    
                    
                    var pay_platform = $.trim($('.iradio_minimal-blue.checked').parent().text());
                    var nick = $('#nick').val();
                    //var confirm_str = '由于' + reason + '，于' + refund_time + '向「' + nick + '」' + pay_platform + '退款' + refund_amount + '元人民币，确认信息无误并提交吗？';
                    var confirm_str = '由于' + reason + '，于' + "<span style=\"color: #F00\">" + refund_time + "<\/span>" + '向「' + nick + '」' + pay_platform + '退款' + "<span style=\"color: #F00\">" + refund_amount + "<\/span>" + '元人民币，确认信息无误并提交吗？';
                    layer.confirm(confirm_str, {
                            btn: ['确定', '取消']
                        }, function (index) {
                            layer.close(index);
                            var form = $('form');
                            form.submit();
                        });
                } else {
                    var form = $('form');
                    form.submit();
                }
            })
		});
SCRIPT);

		$data = DesignerOrder::get('*', ['id' => $id]);
		$data['nick'] = Member::getNickByUid($data['uid']);
		$data['pay_time'] = date('Y-m-d H:i:s', $data['pay_time']);
		$data['refund_time'] = '';

		$packages = DesignerPackage::select(['id', 'package_name'], [
			'status' => DesignerPackage::STATUS_NORMAL
		]);
		$packages = array_column($packages, 'package_name', 'id');

		$form = new Form($data);
		$form->hidden('id');
		$form->text('uid', '用户UID')->setWidth(4, 2)->readonly();
		$form->text('nick', '用户昵称')->setWidth(4, 2)->readonly();
		$form->text('dsn', '设计师订单号')->setWidth(4, 2)->readonly();
		$form->text('other_sn', '第三方订单号')->setWidth(4, 2)->readonly();
		$form->text('pay_time', '支付时间')->setWidth(4, 2)->readonly();
		$form->select('pay_platform', '支付方式')->setWidth(4, 2)->options(self::PAY_PLATFORM)->readOnly();
		$form->select('package_id', '购买套餐')->setWidth(4, 2)->options($packages)->readOnly();
		$form->text('amount', '实际支付金额')->setWidth(4, 2)->readonly();
		$form->text('price', '商品当前价格')->setWidth(4, 2)->readonly();
		$form->text('product_price', '商品定价')->setWidth(4, 2)->readonly();
		$form->text('sale_admin_name', '认领销售的用户名')->setWidth(4, 2)->readonly();
		$form->select('refund_status', '退款状态')->default(self::HAVE_NOT_REFUND)
            ->when(self::HAD_REFUND, function (Form $form) use ($data) {
                if ($data['refund_status'] != DesignerOrder::HAD_REFUND) {
                    $form->decimal('refund_amount', '退款金额')->setWidth(4, 2);
                    $form->datetime('refund_time', '退款时间')->setWidth(4, 2);
                    $form->radio('refund_platform', '退款方式')->options(self::PAY_PLATFORM)->default(DesignerOrder::PAY_PLATFORM_ALI_PAY);
                    $form->text('platform_sn', '交易单号')->attribute('maxlength',50)->setWidth(4, 2);
                    $form->text('reason', '退款原因')->attribute('maxlength',100)->help('最多100个字')->setWidth(6, 2);
                } else {
                    $form->disableReset();
                    $form->disableSubmit();
                }

            })
			->setWidth(4, 2)->options(self::REFUND_STATUS)->required('不能为空');

		$form->action('/admin/DesignerOrder/orders/save');

		return $form->render();
	}

	public function save(Request $request)
	{
		$request = $request->all();
		$id = $request['id'];
		$admin_name = Admin::user()->username;

		$data = [
			'refund_status' => $request['refund_status'],
		];

		$order = DesignerOrder::get('*', [
			'id' => $id
		]);

		if (empty($order)) {
			$error = new MessageBag([
				'title' => '订单不存在'
			]);

			return back()->withInput()->with(compact('error'));
		}

		$auth_info = DesignerAuth::get('*', [
			'uid' => $order['uid']
		]);

		if (!in_array(Admin::user()->username, self::UNLIMITED_LIST) && $auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE) {
			$error = new MessageBag([
				'title' => '仅提供未开通认证的用户退款功能！已认证用户退款，请走其他渠道申请处理'
			]);

			return back()->withInput()->with(compact('error'));
		}

		if ($request['refund_status'] == DesignerOrder::HAD_REFUND) {
		    $ref_verify = OrderRefund::verifyCreateParams($request);
		    if ($ref_verify['result'] == false) {
                $error = new MessageBag([
                    'title' => $ref_verify['msg']
                ]);

                return back()->withInput()->with(compact('error'));
            }

			$data['refund_time'] = time();

			$params = [
				'id' => $id,
				'data' => $data,
				'order' => $order
			];
			DesignerOrder::action(function () use ($params, $request, $order) {
				DesignerOrder::update($params['data'], [
					'id' => $params['id']
				]);

				DesignerAuth::update([
					'is_pay' => DesignerAuth::NOT_PAID
				], [
					'uid' => $params['order']['uid']
				]);

				OrderRefund::createOrderRefund($request, $params['order']);
                DesignerPayService::updateByDsn($order['dsn'], [
                    'status' => DesignerPayService::STATUS_FROZEN
                ]);
			});
		} else {
			DesignerOrder::update($data, [
				'id' => $request['id']
			]);
		}

		$refund_status_text = DesignerOrder::REFUND_STATUS[$data['refund_status']];
		$msg = implode("\n", [
			"操作：修改订单退款状态",
			"设计师uid：{$order['uid']}",
			"修改状态：{$refund_status_text}",
			"订单号：{$order['dsn']}",
			"操作人：{$admin_name}\n",
		]);
        DesignerDingTalkAlert::sendBeerusDesignerAuthAuditMsg2Operator($order['uid'], $msg);

		$success = new MessageBag([
			'title' => '修改成功'
		]);

		return redirect("/admin/DesignerOrder/orders/1/{$request['id']}/edit")->with(compact('success'));
	}

	public function export(Request $request)
	{
		$params = $request->all();

		$condition = $this->condition($params);
		$condition['ORDER'] = ['id' => 'DESC'];
		$data = DesignerOrder::select('*', $condition);

		if (empty($data)) {
			$error = new MessageBag([
				'title' => '暂无符合条件订单数据可导出'
			]);

			return back()->with(compact('error'));
		}

		$user_ids = array_column($data, 'uid');
		$member_info = Member::getUsers($user_ids);

		$auth_info = DesignerAuth::select(['uid', 'designer_type', 'enterprise_name', 'real_name'], [
			'uid' => $user_ids
		]);

		$auth = [];
		foreach ($auth_info as $item) {
			$company = '';
			if ($item['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY) {
				$company = empty($item['enterprise_name']) ? '' : $item['enterprise_name'];
			} elseif (in_array($item['designer_type'],[DesignerAuth::DESIGNER_TYPE_SINGLE,DesignerAuth::DESIGNER_TYPE_COMPANY_EMPLOYEE])) {
				$company = empty($item['real_name']) ? '' : $item['real_name'];
			}
			$auth[$item['uid']] = $company;
		}

		$lists = [];
		foreach ($data as $item) {
			$lists[] = [
				'dsn' => $item['dsn'],
				'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
				'uid' => $item['uid'],
				'company_name' => empty($auth[$item['uid']]) ? '' : $auth[$item['uid']],
				'package_name' => $item['package_name'],
				'create_time' => date('Y-m-d H:i:s', $item['create_time']),
				'order_status' => self::ORDER_STATUS[$item['order_status']],
				'pay_platform' => self::PAY_PLATFORM[$item['pay_platform']],
				'other_sn' => $item['other_sn'],
				'pay_time' => empty($item['pay_time']) ? '' : date('Y-m-d H:i:s', $item['pay_time']),
				'pay_status' => self::PAY_STATUS[$item['pay_status']],
				'refund_status' => self::REFUND_STATUS[$item['refund_status']],
				'amount' => $item['amount'],
				'price' => $item['price'],
				'product_price' => $item['product_price'],
				'start_time' => $item['start_time'],
				'end_time' => $item['end_time'],
				'sale_admin_name' => $item['sale_admin_name'],
				'customer' => $item['customer']
			];
		}

		$header = [
			'设计师订单号','昵称','用户UID','公司名称','服务套餐商品名称','下单时间','订单状态','支付方式','第三方订单号','支付时间','支付状态','退款状态','实际支付金额','商品当前金额','商品定价','服务生效时间','服务到期时间','对接销售','新/老用户'
		];
		$letter = range('A', 'S');
		$excel_obj = new DownExcel();
		$excel_obj->setFileName('设计师订单表 - ' . date('YmdHis'));
		$excel_obj->setSheetTitle('设计师订单表');

		// 设置列宽
		$widths = [
			'A' => 18,
			'B' => 15,
			'C' => 15,
			'D' => 20,
			'E' => 18,
			'F' => 20,
			'G' => 15,
			'H' => 15,
			'I' => 32,
			'J' => 20,
			'K' => 10,
			'L' => 10,
			'M' => 13,
			'N' => 13,
			'O' => 12,
			'P' => 12,
			'Q' => 15,
			'R' => 15,
			'S' => 15
		];

		$excel_obj->setWidth($widths);
		$excel_obj->setDefaultStyleAlignment();

		$excel_obj->create($lists, $header);
	}

    public function exportRefund(Request $request)
    {
        $params = $request->all();

        $condition = $this->condition($params);
        $condition['ORDER'] = ['id' => 'DESC'];
        $data = DesignerOrderRefund::select('*', $condition);

        if (empty($data)) {
            $error = new MessageBag([
                'title' => '暂无符合条件订单数据可导出'
            ]);

            return back()->with(compact('error'));
        }

        $user_ids = array_column($data, 'uid');
        $member_info = Member::getUsers($user_ids);

        $order_ids = array_column($data, 'order_id');
        $order_list = DesignerOrder::select('*', ['id' => $order_ids]);
        $order_map = array_column($order_list, null, 'id');

        $lists = [];
        foreach ($data as $item) {
            $lists[] = [
                'dsn' => $item['dsn'],
                'uid' => $item['uid'],
                'nick' => empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'],
                'package_name' => $item['package_name'],
                'refund_amount' => $item['refund_amount'],
                'refund_time' => date('Y-m-d H:i:s', $item['refund_time']),
                'refund_platform' => DesignerOrderRefund::PAY_PLATFORM[$item['refund_platform']] ?? '',
                'platform_sn' => $item['platform_sn'],
                'reason' => $item['reason'],
                'admin_name' => Admin::user()->find($item['admin_id'])->name ?: $item['admin_name'],
                'sale_admin_name' => isset($order_map[$item['order_id']]) ? $order_map[$item['order_id']]['sale_admin_name'] : '',
                'customer' => isset($order_map[$item['order_id']]) ? $order_map[$item['order_id']]['customer'] : '',
            ];
        }

        $header = [
            '设计师订单号','UID','昵称','套餐名称','退款金额','退款时间','退款方式','交易单号','退款原因','退款操作人','认领销售的用户名','新/老用户'
        ];
        $excel_obj = new DownExcel();
        $excel_obj->setFileName('设计师退款订单表 - ' . date('YmdHis'));
        $excel_obj->setSheetTitle('设计师退款订单表');

        // 设置列宽
        $widths = [
            'A' => 32,
            'B' => 15,
            'C' => 15,
            'D' => 20,
            'E' => 18,
            'F' => 20,
            'G' => 15,
            'H' => 32,
            'I' => 32,
            'J' => 15,
            'K' => 18,
            'L' => 15,
        ];

        $excel_obj->setWidth($widths);
        $excel_obj->setDefaultStyleAlignment();
        $excel_obj->setTextFormat('A');
        $excel_obj->setTextFormat('H');

        $excel_obj->create($lists, $header);
    }

	public function condition($params)
	{
		$condition = [];
		if (!empty($params['uid'])) {
			$condition['uid'] = $params['uid'];
		}

		if (!empty($params['nick'])) {
			$uid = User::getUidByNick($params['nick']);
			$condition['uid'] = $uid;
		}

		if (!empty($params['pay_status'])) {
			$condition['pay_status'] = $params['pay_status'];
		}

		if (!empty($params['refund_status'])) {
			$condition['refund_status'] = $params['refund_status'];
		}

		if (!empty($params['pay_platform'])) {
			$condition['pay_platform'] = $params['pay_platform'];
		}

		if (!empty($params['pay_time']['start'])) {
			$condition['pay_time[>=]'] = strtotime($params['pay_time']['start']. ' 00:00:00');
		}

		if (!empty($params['pay_time']['end'])) {
			$condition['pay_time[<=]'] = strtotime($params['pay_time']['end']. ' 23:59:59');
		}

		if (!empty($params['pay_time']['>='])) {
			$condition['pay_time[>=]'] = $params['pay_time']['>='];
		}

		if (!empty($params['pay_time']['<='])) {
			$condition['pay_time[<=]'] = $params['pay_time']['<='];
		}

        if (!empty($params['dsn'])) {
            $condition['dsn'] = $params['dsn'];
        }

        if (!empty($params['refund_platform'])) {
            $condition['refund_platform'] = $params['refund_platform'];
        }

        if (!empty($params['refund_time']['start'])) {
            $condition['refund_time[>=]'] = strtotime($params['refund_time']['start']. ' 00:00:00');
        }

        if (!empty($params['refund_time']['end'])) {
            $condition['refund_time[<=]'] = strtotime($params['refund_time']['end']. ' 23:59:59');
        }

		return $condition;
	}

	public static function getPicUrl($pic_id)
	{
		if (empty($pic_id)) {
			return '';
		} else {
			return  "https://img.haohaozhu.cn/Op-imageShow/{$pic_id}?iv=1";
		}
	}

	public function editOffline(Request $request, Content $content, $tab_id = 1)
	{
		// 订单套餐价格下拉联动
		Admin::script(<<<SCRIPT
		$(document).ready(function(){  
		    $('.package_id').change(function(){  
		        let selectText = $(this).children('option:selected').text();
		        let textArr = selectText.split("￥");
		        $("#amount").val(textArr[1]);
		    })  
		    
		    $(':submit').click(function(e){
		        var uid = $('#uid').val();		        
		        var pay_time = $('#pay_time').val();
		        var pay_platform = $.trim($('.iradio_minimal-blue.checked').parent().text());
		        if (uid == '' || pay_time == '' || pay_platform == '') {
		            return;
		        }
		        if ($('.select2-selection__rendered').attr('title') == undefined) {
		            return;
		        }
		        var package_info = $('.select2-selection__rendered').attr('title');
		        var p_key = package_info.indexOf('￥');
		        var package_name = $.trim(package_info.substring(0,p_key));
		        var package_amount = $.trim(package_info.substring(p_key));
		        var real_amount = $('#amount').val();
		        
		        e.preventDefault();
		        
		        var nick = ' ';
		        var url = '/admin/DesignerOrder/orders/getUserInfo?uid=' + uid
                $.get(url, function (result) {
                    if (result.code == 1) {
                        nick = result.data.nick;
                    }
                    
                    var confirm_str = "设计师「" + nick + "」于" + "<span style=\"color: #F00\">" + pay_time + "<\/span>" + pay_platform 
                        + "实付" + "<span style=\"color: #F00\">" + real_amount + "<\/span>" + "元人民币购买「" + package_name + "<span style=\"color: #F00\">" + package_amount + "<\/span>"+"」套餐";
                    console.log(confirm_str);
                    layer.confirm(confirm_str, {
                        btn: ['确定', '取消'],
                        title: "确认以下信息填写无误并提交吗？"
                    }, function (index) {
                        layer.close(index);
                        var form = $('form');
                        form.submit();
                    });
                });
                
                
		    })
		});
SCRIPT);

		$packages = DesignerPackage::listByCondition([
			'status' => DesignerPackage::STATUS_NORMAL,
			'version' => 'v2'
		]);

		$package_select = $operator = $value = [];
		foreach ($packages as $item) {
			$package_select[$item['id']] = $item['package_name']. '  ￥'. $item['price'];
			$operator[] = $item['id'];
			$value[] = $item['price'];
		}

		$header = '录入线下付款订单';
		$form = new Form();
		$form->text('uid', '用户UID')->setWidth(4, 2)->required('不能为空');
		$form->select('package_id', '付费套餐')->setWidth(4, 2)
			->options($package_select)
			->required('不能为空');
		$form->number('amount', '实付金额')
			->setWidth(4, 2)
			->required('不能为空');
		$form->radio('pay_platform', '支付方式')->options(self::PAY_PLATFORM)->default(DesignerOrder::PAY_PLATFORM_ALI_PAY)->required('不能为空');
		$form->date('pay_time', '支付时间')->setWidth(4, 2)->required('不能为空');
		$form->imgUpload('pay_proof', '汇款凭证截图')->setWidth(4, 2);
		$form->text('other_sn', '流水号')->setWidth(4, 2)->help('请填写公司财务提供的流水号，用于对账');

		$form->action('/admin/DesignerOrder/orders/saveOffline');
		$tab = new Tab();
		$tab->add('录入订单', $form->render());
		return $content->header($header)
			->description('<b style="color: red">（注意：仅供正常付费套餐录入，不支持促销活动套餐录入！）</b>')
			->breadcrumb([
				'text' => '线下付款订单',
				'url' => route('order.list', ['tab_id' => 2])
			], ['text' => $header])->row($tab);
	}

	public function saveOffline(Request $request)
	{
		$request = $request->all();
		$uid = $request['uid'];
		$package_id = $request['package_id'];

		if ($request['pay_time'] > date('Y-m-d')) {
			$error = new MessageBag([
				'title' => '支付时间必须小于等于当前时间'
			]);

			return back()->withInput()->with(compact('error'));
		}

		if (empty($request['pay_proof'])) {
			$error = new MessageBag([
				'title' => '请上传付款凭证'
			]);

			return back()->withInput()->with(compact('error'));
		}

		// 检查设计师身份和购买的套餐是否合法
		$package_info = DesignerPackage::getById($package_id);
		if (empty($package_info)) {
			$error = new MessageBag([
				'title' => '无效的套餐'
			]);

			return back()->withInput()->with(compact('error'));
		}

		// 检查设计师的案例和资料是否已通过审核
		$auth_info = DesignerAuth::getByUId($uid);
		if (empty($auth_info)) {
			$error = new MessageBag([
				'title' => '当前用户没有上传认证资料'
			]);

			return back()->withInput()->with(compact('error'));
		} else {
			if ($auth_info['house_article_audit_status'] != DesignerAuth::STATUS_AUDIT_PASS
				|| $auth_info['identity_info_audit_status'] != DesignerAuth::STATUS_AUDIT_PASS) {
				$error = new MessageBag([
					'title' => '用户的案例或者资料还未通过审核'
				]);

				return back()->withInput()->with(compact('error'));
			}

			if (($auth_info['designer_type'] == DesignerAuth::DESIGNER_TYPE_COMPANY &&
					$package_info['package_type'] != DesignerPackage::PACKAGE_TYPE_COMPANY) ||
				(in_array((int)$auth_info['designer_type'], [
						DesignerAuth::DESIGNER_TYPE_SINGLE,
						DesignerAuth::DESIGNER_TYPE_COMPANY_EMPLOYEE
					]) && $package_info['package_type'] != DesignerPackage::PACKAGE_TYPE_PERSON)) {
				$error = new MessageBag([
					'title' => '选择的套餐和设计师认证身份不符合！！！'
				]);

				return back()->withInput()->with(compact('error'));
			}
		}

		// 限制一个月内因为误操作而重复录入订单
        // 若一个月内没录入过 或 录入过且订单状态为「已退款」可继续录入
        // 若一个月内录入过且订单状态为非「已退款」则不可重复录入
        $aOldOrder = DesignerOrder::get('*', [
            'uid' => $uid,
            'refund_status[<]' => DesignerOrder::HAD_REFUND,
            'pay_status' => DesignerOrder::PAY_STATUS_PAID,
            'create_time[>=]' => time() - 30*24*3600,
        ]);
		if (!empty($aOldOrder)) {
            $error = new MessageBag([
                'title' => '重复操作：近一个月内当前用户已经录入过一笔订单'
            ]);
            return back()->withInput()->with(compact('error'));
        }

		$insert_data = [
			'uid' => $uid,
			'package_type' => $package_info['type'],
			'package_id' => $package_id,
			'pay_proof' => $request['pay_proof'],
			'amount' => $request['amount'],
			'add_time' => time(),
			'edit_time' => time(),
			'status' => DesignerOfflinePay::STATUS_NORMAL,
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username
		];

		$result = DesignerOfflinePay::insert($insert_data);
		$nick = Member::getNickByUid($uid);

		if ($result) {
			$dsn = OrderSN::createOrderSN($uid);
			$sale_bind = AdmSaleBind::getInfoByUid($uid);

			$designer_info = Designer::getOneRow($uid);
			$customer = empty($designer_info) ? '新用户' : '老用户';

			$data = [
				'dsn' => $dsn,
				'uid' => $uid,
				'nick' => $nick,
				'package_id' => $package_id,
				'package_name' => $package_info['package_name'],
				'create_time' => time(),
				'order_status' => DesignerOrder::ORDER_STATUS_FINISHED,
				'pay_platform' => $request['pay_platform'],
				'other_sn' => $request['other_sn'],
				'pay_time' => strtotime($request['pay_time']),
				'pay_status' => DesignerOrder::PAY_STATUS_PAID,
				'amount' => $request['amount'],
				'price' => $request['amount'],
				'product_price' => $package_info['price'],
				'settle_time' => 0,
				'refund_time' => 0,
				'sale_admin_name' => $sale_bind ? $sale_bind['admin_name'] : '',
				'order_type' => DesignerOrder::ORDER_TYPE_COMMON,
				'customer' => $customer
			];

			$order_data = DesignerOrder::insert($data);
			DesignerAuth::updateInfo($uid, [
				'plan_type' => DesignerService::SERVICE_TYPE_PAY,
				'is_pay' => DesignerAuth::HAVE_PAID
			]);

			if (!empty($order_data)) {
				try {
					if ($auth_info['auth_status'] == DesignerAuth::STATUS_AUTH_COMPLETE) {
					    $lastPackageId = 0;
						$normal_service = DesignerPayService::getNormalService($uid);
						$start_time = time();
						if (!empty($normal_service)) {
                            $lastPackageId = $normal_service['package_id'];
							$start_time = $normal_service['end_time'];

							// 在开通新服务之前，将上一段服务记录终止掉
							$update_data = [
								'status' => DesignerPayService::STATUS_END,
							];
							DesignerPayService::updateById($normal_service['id'], $update_data);
						}
						$end_time = DesignerService::calculationServiceTime(
							DesignerService::SERVICE_TIME['y'],
							$start_time
						);

						$service_data = [
							'dsn' => $dsn,
							'uid' => $uid,
							'nick' => $nick,
							'package_id' => $package_id,
							'package_name' => $package_info['package_name'],
							'start_time' => $start_time,
							'end_time' => $end_time,
							'service_type' => DesignerService::SERVICE_TYPE_PAY,
						];
						DesignerPayService::insert($service_data);

						// 如果上一段认证还未到期，则认证时间取上一段的开始时间
//						if ($normal_service['end_time'] >= time()) {
//							$start_time = $normal_service['start_time'];
//						}

						// 同步认证时间及到期时间
						$update_data = [
							'auth_status' => DesignerAuth::STATUS_AUTH_COMPLETE,
//							'auth_time' => $start_time,
							'expire_time' => $end_time,
							'plan_type' => DesignerService::SERVICE_TYPE_PAY,
							'is_pay' => DesignerAuth::HAVE_PAID,
						];
						DesignerAuth::updateInfo($uid, $update_data);
						DesignerEquityService::addEquity($uid, $request['package_id']);

                        // 发送认证礼包 NEED:停止推送By陈安阳
//                        AuthService::sendAuthGift($uid);

                        // 增加续费降级标记
                        if (!DesignerEquityService::addDownMark($uid, $lastPackageId, $package_id)) {
                            throw new \Exception('降级失败');
                        }
                        DesignerEquityService::sendRenewDownNotice2Operator($uid, $lastPackageId, $package_id, $nick);
					}
				} catch (\Exception $e) {
					$error = new MessageBag([
						'title' => '录入失败：'. $e->getMessage()
					]);

					return back()->withInput()->with(compact('error'));
				}
			}

			$success = new MessageBag([
				'title' => '录入成功'
			]);

			return back()->withInput()->with(compact('success'));
		} else {
			$error = new MessageBag([
				'title' => '录入失败'
			]);

			return back()->withInput()->with(compact('error'));
		}
	}

	public static function getUserInfo(Request $request) {
	    $user_info = ['nick' => ''];
	    $uid = $request = $request->input('uid');
	    if (!empty($uid)) {
            $user = Member::getUser($uid);
            $user_info['nick'] = $user ? $user['nick'] : '';
        }
        return [
            'code' => 1,
            'data' => $user_info
        ];
    }
}
